/**************************************************************************

Game Editor - The Cross Platform Game Creation Tool
Copyright (C) 2009  Makslane Araujo Rodrigues, http://game-editor.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

If GPL v3 does not work for you, we offer a "non-GPL" license 
More info at http://game-editor.com/License
Be a Game Editor developer: http://game-editor.com/Sharing_Software_Revenues_in_Open_Source

***************************************************************************/


/////////////////////////////////////////////////////////////////////////////
// Name:        MainFrame.cpp
// Purpose:     
// Author:      
// Modified by: 
// Created:     01/08/06 14:25:46
// RCS-ID:      
// Copyright:   
// Licence:     
/////////////////////////////////////////////////////////////////////////////

// Generated by DialogBlocks (unregistered), 01/08/06 14:25:46

#if defined(__GNUG__) && !defined(__APPLE__)
#pragma implementation "MainFrame.h"
#endif

#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

#if !wxUSE_GLCANVAS
#error "OpenGL required: set wxUSE_GLCANVAS to 1 and rebuild the library"
#endif

#include "AppDelegate.h"
#include "HelloWorldScene.h"
#include "MyEGLView.h"

USING_NS_CC;

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#include "wx/ifm/dragndrop.h"
#include "wx/sysopt.h"
#include "wx/glcanvas.h"
#include "wx/cmdline.h"
#include "wx/wfstream.h"
#include "wx/zstream.h"
#include "wx/txtstrm.h"

#include "wx/config.h"

#include "oxDefs.h"

#include "MainFrame.h"

#include "GLCanvas.h"

#include "Tree.h"
#include "Hierarchy.h"
#include "Project.h"

#include "Inspector.h"

#include "Console.h"


////@begin includes
////@end includes

#include "OryxApp.h"



////@begin XPM images
////@end XPM images




#define MENU_PANEL_BASE_ID 12345
#define MENU_PANEL_LAYOUT_ID (MENU_PANEL_BASE_ID + 100)






/*!
 * MainFrame type definition
 */

IMPLEMENT_CLASS( MainFrame, wxFrame )

/*!
 * MainFrame event table definition
 */

BEGIN_EVENT_TABLE( MainFrame, wxFrame )

////@begin MainFrame event table entries
    EVT_CLOSE( MainFrame::OnCloseWindow )
    EVT_ERASE_BACKGROUND( MainFrame::OnEraseBackground )

	EVT_MENU( XRCID("ID_MENU_NEW"), MainFrame::OnMenuNewClick )

	EVT_MENU( XRCID("ID_MENU_OPEN"), MainFrame::OnMenuOpenClick )

    EVT_MENU( XRCID("ID_MENU_EXIT"), MainFrame::OnMenuExitClick )

    EVT_MENU( XRCID("ID_MENU_TITLE_BAR"), MainFrame::OnMenuTitleBarClick )

    EVT_MENU( XRCID("ID_MENU_LAYOUT_RESET"), MainFrame::OnMenuLayoutResetClick )

    EVT_MENU( XRCID("ID_GAME_MODE"), MainFrame::OnGameModeClick )

	EVT_MENU( XRCID("ID_NEW_GAMEOBJECT"), MainFrame::OnGameObjectClick )

	EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, MainFrame::OnMRUFile)

////@end MainFrame event table entries

	EVT_ACTIVATE(MainFrame::OnActivate)
	EVT_MOVE(MainFrame::OnMove)
	EVT_SIZE(MainFrame::OnSize)
	EVT_ICONIZE(MainFrame::OnIconize) 
	EVT_MAXIMIZE(MainFrame::OnMaximize) 

	EVT_MENU_OPEN(MainFrame::OnMenuOpen)	
	EVT_MENU_RANGE(MENU_PANEL_BASE_ID, MENU_PANEL_BASE_ID + 32, MainFrame::OnMenuPanel)
	EVT_MENU_RANGE(MENU_PANEL_LAYOUT_ID, MENU_PANEL_LAYOUT_ID + 99, MainFrame::OnMenuLoadLayout)

	/********** oryx
	EVT_MENU( XRCID("ID_MENU_LAYOUT_SAVE"), MainFrame::OnMenuLayoutSaveClick )
    EVT_MENU( XRCID("ID_MENU_LAYOUT_SAVE_AS"), MainFrame::OnMenuLayoutSaveAsClick )
    EVT_MENU( XRCID("ID_MENU_LAYOUT_DELETE"), MainFrame::OnMenuLayoutDeleteClick )
    EVT_MENU( XRCID("ID_MENU_LAYOUT_RESTORE"), MainFrame::OnMenuLayoutRestoreClick )
	************/


	EVT_DROP_FILES(MainFrame::OnDropFiles)
	EVT_LAYOUT_STATE(wxID_ANY, MainFrame::OnLayoutState)

	/*** oryx
	EVT_COMMAND(wxID_ANY, wxEVT_BEHAVIOR_BLOCK_SELECTED, MainFrame::OnBehaviorBlockSelected)
	***/


END_EVENT_TABLE()

/*!
 * MainFrame constructors
 */

MainFrame *MainFrame::mainFrame = NULL;

MainFrame::MainFrame( )
{
	mainFrame = this;
	m_ifm = NULL;
	bMaximized = false;
}

MainFrame::MainFrame( wxString _applicationDir, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
	mainFrame = this;
	//statusBar = NULL;
	m_ifm = NULL;
	
	bMaximized = false;
	applicationDir = _applicationDir;

    Create( NULL, id, caption, pos, size, style );
}

MainFrame::~MainFrame( )
{
	mainFrame = NULL;
	m_root_panel = NULL;
}

/*!
 * MainFrame creator
 */

bool MainFrame::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
	//Allow 24bits icons
	/*if(wxTheApp->GetComCtl32Version() >= 600 && ::wxDisplayDepth() >= 24)
	{
		wxSystemOptions::SetOption(wxT("msw.remap"), 2);
	}
	else*/
	{
		//Disable system theme remap (without this, icons don't look good)
		wxSystemOptions::SetOption(wxT("msw.remap"), 0);
	}

////@begin MainFrame member initialisation
////@end MainFrame member initialisation

////@begin MainFrame creation
    SetParent(parent);
    CreateControls();
    Centre();
////@end MainFrame creation

	//Create status bar
// 	statusBar = NULL; //Need any status bar? statusBar = new wxGedStatusBar(this, wxID_ANY, wxST_SIZEGRIP);	
// 	SetStatusBar(statusBar);

	int widths[] = { -1 };

	if(GetStatusBar()) 
	{
		GetStatusBar()->SetFieldsCount(WXSIZEOF(widths), widths);
		GetStatusBar()->SetStatusText(wxT("Ready"), 0);
	}
	

	//Setup tool bar color
	if(GetToolBar()) GetToolBar()->SetBackgroundColour(wxBackground_Pen);
	

    Setup_wxIFM();

	DragAcceptFiles(true);
      
    return true;
}


void MainFrame::Setup_wxIFM()
{
    // panel as the only child
    m_root_panel = new wxPanel(this);

    // connect erase background for the root panel to get flicker free drawing back
    m_root_panel->Connect(wxEVT_ERASE_BACKGROUND, wxEraseEventHandler(MainFrame::OnEraseBackground));
		
    // create the interface management object
    m_ifm = new wxInterfaceManager(m_root_panel);

    m_ifm->Initialize(true/*, IFM_NO_RESIZE_UPDATE*/);
    //m_ifm->SetInterfaceRect(wxRect(50,50,800,800));

	wxIFMDefaultDockingPlugin::setUseTargetButtons(false);
	


	// demonstrate using the configuration api to change the font for captions and tabs
    // Note that wxSYS_DEFAULT_GUI_FONT is the default setting, so this won't actually
    // change the appearance of the demo, its only for demonstrating the api
	// Set the colors before create the panels to avoid system colors in close buttons

    wxIFMCaptionConfig &caption_config = wxIFMDefaultPanelPlugin::GetCaptionConfig();

    caption_config.set_font(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
	caption_config.set_font_colour(colorCaptionText);

	

	


	

    wxIFMTabConfig &tab_config = wxIFMDefaultPanelPlugin::GetTabConfig();
    tab_config.set_font(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
	tab_config.set_rounding_factor(-1);
	tab_config.set_top(true);



    // specify the status bar pane to use for displaying messages
    if(GetStatusBar()) m_ifm->SetStatusMessagePane(GetStatusBar(), 0);


	// First we need to create the add child data object
    // We are using the default interface, so we use its child data object
    wxIFMDefaultChildData data;

    
	// add some windows in a format most common to programming IDE's

	 
	//pBehavior = new Behavior(m_root_panel);




	///////////////////////////////////////
	//Behavior
// 	wxDocManager *m_DocManager = new wxDocManager;
// 	wxDocTemplate * docTemplate = new wxDocTemplate(m_DocManager, _("Jigsaw Scene"),
// 		wxT("*.jigscene;*.xml"), wxEmptyString, wxT("jigscene"), 
// 		wxT("wxJigsawEditorDoc"), wxT("wxJigsawEditorView"),
// 		CLASSINFO(wxJigsawEditorDocument), CLASSINFO(wxJigsawEditorView));
// 	wxUnusedVar(docTemplate);
// 	m_DocManager->SetMaxDocsOpen(1);
// 	pBehavior = new wxJigsawEditorMainFrame( m_DocManager, (wxFrame*)m_root_panel, wxJigsawEditorMainFrame::ID_WXJIGSAWEDITORMAINFRAME, SYMBOL_WXJIGSAWEDITORMAINFRAME_TITLE, SYMBOL_WXJIGSAWEDITORMAINFRAME_POSITION, SYMBOL_WXJIGSAWEDITORMAINFRAME_SIZE, wxTAB_TRAVERSAL | wxNO_BORDER | wxFRAME_TOOL_WINDOW);
// 	pBehavior->SetExtraStyle(0);		
// 	m_DocManager->CreateDocument(wxEmptyString, wxDOC_NEW );		
	///////////////////////////////////////

	GLCanvas *pGLCavas = new GLCanvas(m_root_panel);
	
	wxStaticText *pInspector = new wxStaticText(m_root_panel, wxID_ANY, wxT("Inspector"));

	Hierarchy *pHierarchy = new Hierarchy(m_root_panel, oxHierarchy_Ctrl);
	wxStaticText *pProject = new wxStaticText(m_root_panel, wxID_ANY, wxT("Project"));

	wxTextCtrl *pConsole = new wxTextCtrl(m_root_panel, wxID_ANY, wxT(""),
		wxDefaultPosition, wxDefaultSize,
		wxTE_MULTILINE | wxSUNKEN_BORDER);
#if wxUSE_LOG
#ifdef __WXMOTIF__
	// For some reason, we get a memcpy crash in wxLogStream::DoLogStream
	// on gcc/wxMotif, if we use wxLogTextCtl. Maybe it's just gcc?
	delete wxLog::SetActiveTarget(new wxLogStderr);
#else
	// set our text control as the log target
	wxLogTextCtrl *logWindow = new wxLogTextCtrl(pConsole);
	delete wxLog::SetActiveTarget(logWindow);
#endif
#endif // wxUSE_LOG

	//Increase CURRENT_LAYOUT_VERSION when add a new panel

	data.m_name = wxT("Inspector");
	data.m_type = IFM_CHILD_GENERIC;
	data.m_desiredSize.Set(200, GetSize().GetHeight() - pProject->GetMaxHeight() - 64	);
	data.m_minSize.Set(120, 100);
	data.m_maxSize.Set(350, IFM_NO_MAXIMUM);
	data.m_orientation = IFM_ORIENTATION_RIGHT; // bottom of the frame
	data.m_tabify = false; // make this child a tab of the previously added child
	data.m_hideable = true;
	data.bCanDrag = true;
	data.m_newRow = true;
	data.m_child = pInspector;  
	AppendPanelToMenu(data.m_child, data.m_name);
	data.m_newRow = true;
	m_ifm->AddChild(&data);

	wxIFMTab *propertiesTab = wxIFMTab::lastCreatedTab;

    data.m_name = wxT("Hierarchy");
    data.m_type = IFM_CHILD_GENERIC;
	data.m_desiredSize.Set(200, GetSize().GetHeight() - pHierarchy->GetMaxHeight() - 64	);
    data.m_minSize.Set(120, 100);
	data.m_maxSize.Set(350, IFM_NO_MAXIMUM);
    data.m_orientation = IFM_ORIENTATION_LEFT; // bottom of the frame
	data.m_tabify = false; // make this child a tab of the previously added child
	data.m_hideable = true;
	data.bCanDrag = true;
    data.m_child = pHierarchy;  
	AppendPanelToMenu(data.m_child, data.m_name);
	data.m_newRow = true;
    m_ifm->AddChild(&data);
    
	data.m_name = wxT("Project");
	data.m_type = IFM_CHILD_GENERIC;
	data.m_desiredSize.Set(200, GetSize().GetHeight() - pProject->GetMaxHeight() - 64	);
	data.m_minSize.Set(120, 100);
	data.m_maxSize.Set(350, IFM_NO_MAXIMUM);
	data.m_orientation = IFM_ORIENTATION_LEFT; // bottom of the frame
	data.m_tabify = true; // make this child a tab of the previously added child
	data.m_hideable = true;
	data.bCanDrag = true;
	data.m_child = pProject;  
	AppendPanelToMenu(data.m_child, data.m_name);
	data.m_newRow = true;
	m_ifm->AddChild(&data);



	m_ifm->SetContentWindow( pGLCavas );
	 

    data.m_name = wxT("Console");
    data.m_minSize.Set(120, 100);
	data.m_maxSize = IFM_NO_MAXIMUM_SIZE;
	data.m_orientation = IFM_ORIENTATION_BOTTOM; 
    data.m_tabify = false; // make this a tab
	data.m_hideable = true;
	data.m_newRow = false;
	data.bCanDrag = true;
	
	data.m_child = pConsole;
	data.m_desiredSize.Set(600, 150);
	AppendPanelToMenu(data.m_child, data.m_name);

    m_ifm->AddChild(&data);



	//Select Stage
// 	wxIFMSelectTabEvent event1(sceneTab->m_tab->m_parent, sceneTab, false);
// 	m_ifm->GetActiveIP()->ProcessPluginEvent(event1);

	//Select Properties
	wxIFMSelectTabEvent event2(propertiesTab->m_tab->m_parent, propertiesTab, false);
	m_ifm->GetActiveIP()->ProcessPluginEvent(event2);


    // we are done creating children, now lets make a textbox for the content window
	/*wxTextCtrl *content = new wxTextCtrl(m_root_panel, wxID_ANY, wxT("This is the content window"),
        wxPoint(), wxSize(), wxTE_MULTILINE | wxTE_WORDWRAP);
    m_ifm->SetContentWindow( content );*/ 

    

    

	//Layout
	//This version will works only with one layout
	//and the Reset Layout option
	//To works with multiple layouts, put this menu definition in the xrc file:
	/*<object class="wxMenu" name="ID_MENU_LAYOUTS">
        <label>Layouts</label>
        <object class="wxMenuItem" name="ID_MENU_LAYOUT_SAVE">
            <label>Save</label>
        </object>
        <object class="wxMenuItem" name="ID_MENU_LAYOUT_SAVE_AS">
            <label>Save As...</label>
        </object>
        <object class="wxMenuItem" name="ID_MENU_LAYOUT_DELETE">
            <label>Delete ...</label>
        </object>
        <object class="wxMenuItem" name="ID_MENU_LAYOUT_RESTORE">
            <label>Restore</label>
        </object>
        <object class="separator">
        </object>
    </object>*/

	layoutControl = new wxIFMLayoutControl();
	layoutControl->Init(applicationDir + wxT("layout.dat"));
	

	wxStringList layoutList(layoutControl->GetLayoutList());

	for(unsigned int i = 0; i < layoutList.size(); i++)
	{
		AppendLayoutToMenu(layoutList[i]);
	}

	SetupMRU();

	m_ifm->UpdateConfiguration();

	/***** oryx
	//Set focus to stage, if active
	if(sdlPanel && sdlPanel->IsShown()) 
	{
		sdlPanel->SetFocus();
	}
	********/

	if (pGLCavas && pGLCavas->IsShown())
	{
		pGLCavas->SetFocus();
	}

	//Limit min frame size
	SetSizeHints(750, 550);	
}



/*!
 * Control creation for MainFrame
 */

void MainFrame::CreateControls()
{    
////@begin MainFrame content construction
    // Generated by DialogBlocks, 02/07/06 18:11:49 (unregistered)

    wxXmlResource::Get()->LoadFrame(this, GetParent(), wxT("ID_FRAME"));
////@end MainFrame content construction

    // Create custom windows not generated automatically here.

////@begin MainFrame content initialisation

////@end MainFrame content initialisation
}

/*!
 * Should we show tooltips?
 */

bool MainFrame::ShowToolTips()
{
    return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap MainFrame::GetBitmapResource( const wxString& name )
{
    // Bitmap retrieval
////@begin MainFrame bitmap retrieval
    wxUnusedVar(name);
    if (name == wxT("open_b.gif"))
    {
        wxBitmap bitmap(_T("open_b.gif"), wxBITMAP_TYPE_GIF);
        return bitmap;
    }
    else if (name == wxT("save_b.gif"))
    {
        wxBitmap bitmap(_T("save_b.gif"), wxBITMAP_TYPE_GIF);
        return bitmap;
    }
    else if (name == wxT("play_b.gif"))
    {
        wxBitmap bitmap(_T("play_b.gif"), wxBITMAP_TYPE_GIF);
        return bitmap;
    }
    return wxNullBitmap;
////@end MainFrame bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon MainFrame::GetIconResource( const wxString& name )
{
    // Icon retrieval
////@begin MainFrame icon retrieval
    wxUnusedVar(name);
    return wxNullIcon;
////@end MainFrame icon retrieval
}
/*!
 * wxEVT_ERASE_BACKGROUND event handler for ID_FRAME
 */

void MainFrame::OnEraseBackground( wxEraseEvent& event )
{

}


/*!
 * wxEVT_CLOSE_WINDOW event handler for ID_FRAME
 */

void MainFrame::OnCloseWindow( wxCloseEvent& event )
{
	/***** oryx
	//Can exit?
	if(event.CanVeto())
	{		
		if(GameControl::Get()->getGameMode())
		{
			event.Veto();
			MainPanel::Get()->OnKeyUp(SDLK_ESCAPE);
			return;
		}
		else if(GameControl::Get()->Modified())
		{
			int answer = wxMessageBox(wxT("This will discard the current game.\nProceed anyway?"), wxT("Confirm"), wxYES_NO | wxCENTRE);
			
			if(answer != wxYES)
			{
				event.Veto();
				return;
			}			
		}
	}
	***********/


	//Save current layout
	if(layoutControl)
	{
		layoutControl->SaveCurrent();
		layoutControl->Save();
		delete layoutControl;
		layoutControl = NULL;
	}

	if(m_ifm)
	{
		// shut down the interface management object
		m_ifm->Shutdown();
		
		// it is now safe to delete it
		delete m_ifm;
		m_ifm = NULL;
	}

	/**** oryx
	if(statusBar)
	{
 		delete statusBar;
		statusBar = NULL;
	}
	***/

	//delete sdlPanel;

    event.Skip();
}


void MainFrame::OnActivate(wxActivateEvent& event)
{
    /*if(m_ifm && event.GetActive()) 
	{
		m_ifm->Update(IFM_DEFAULT_RECT, true);
	}*/

	/*if(event.GetActive()) 
	{
		wxShowEvent event(GetId(), true);
		event.SetEventObject(this);
		
		GetEventHandler()->ProcessEvent(event);
	}*/

	
	/***** oryx
	if(GameControl::Get() && GameControl::Get()->getGameMode())
	{
		if(GameControl::Get()->getFullScreen())
		{
		}
		else
		{
			if(event.GetActive())
			{
				SetupSDLPanelGameModePosition();
				GameControl::Get()->SuspendGame(false);
			}
			else if(GameControl::Get()->getSuspendGameIfLostFocus())
			{
				GameControl::Get()->SuspendGame(true);
			}
		}
	}

	oryx ********/
}

bool MainFrame::Show(bool show)
{
	if(!show) wxWindowBase::Show(true); //Without this, can fail in the Show function
	return wxFrame::Show(show);
}

void MainFrame::OnMenuOpen(wxMenuEvent &event) 
{
    wxMenu *menuTitleBar = NULL, *menuLayout = NULL;
	if(!GetMenuBar()) return;

	GetMenuBar()->FindItem(XRCID("ID_MENU_TITLE_BAR"), &menuTitleBar);
	GetMenuBar()->FindItem(XRCID("ID_MENU_LAYOUT_DELETE"), &menuLayout);

	if(menuTitleBar == event.GetMenu())
	{
		wxwxMenuItemListNode *node;

		//Update panel itens
		node = menuTitleBar->GetMenuItems().GetFirst(); 

        while (node) 
        { 
                wxMenuItem *mi = node->GetData(); 
				wxWindow *panel = m_panels[mi->GetId()];				

				if(panel && mi->IsCheckable())
				{
					mi->Check(m_ifm->IsChildVisible(panel));
				}
				else if(mi->GetId() == XRCID("ID_MENU_TITLE_BAR"))
				{
					mi->Check(GetWindowStyle() & (wxCAPTION | wxSYSTEM_MENU | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX));
				}
                
                node = node->GetNext(); 
        } 
				

		//Update Delete
		if(menuLayout)
		{
			node = menuLayout->GetMenuItems().GetFirst(); 
			
			while (node) 
			{ 
                wxMenuItem *mi = node->GetData(); 
				if(mi->GetId() == XRCID("ID_MENU_LAYOUT_DELETE"))
				{
					//Set state
					mi->Enable(layoutControl->size() > 1);
					break;
				}
                
                node = node->GetNext(); 
			}
		}

		
	}
	else
	{
		event.Skip();
	}
	
}

void MainFrame::OnMenuPanel(wxCommandEvent &event)
{
    // hide or show the appropriate window

    m_ifm->ShowChild(m_panels[event.GetId()], event.IsChecked(), true);
}

void MainFrame::HidePanels()
{
	for( wxWindowMap::iterator i = m_panels.begin(), end = m_panels.end(); i != end; ++i )
    {
        m_ifm->ShowChild(i->second, false);
    }

	m_ifm->UpdateConfiguration();
}

void MainFrame::OnMenuLoadLayout(wxCommandEvent &event)
{
	layoutControl->LoadLayout(m_layouts[event.GetId()]);
}

void MainFrame::AppendPanelToMenu(wxWindow *window, wxString &name)
{
	if(GetMenuBar())
	{
		//Append menu
		wxMenu *menu = NULL;
		wxMenuItem *menuItem = GetMenuBar()->FindItem(XRCID("ID_MENU_TITLE_BAR"), &menu);
		
		if(menuItem && menu)
		{
			int id = MENU_PANEL_BASE_ID + m_panels.size();
			
			menu->AppendCheckItem(id, name);
			m_panels[id] = window;
		}
	}
}

void MainFrame::AppendLayoutToMenu(wxString name)
{
	if(GetMenuBar())
	{
		//Append menu
		wxMenu *menu = NULL;
		wxMenuItem *menuItem = GetMenuBar()->FindItem(XRCID("ID_MENU_LAYOUT_DELETE"), &menu);
		
		if(menuItem && menu)
		{
			static int id = MENU_PANEL_LAYOUT_ID;// + layoutControl->size();
			
			menu->Append(id, name);
			m_layouts[id] = name;
			id++;
		}
	}
}

void MainFrame::RemoveLayoutFromMenu(wxString name)
{
	if(GetMenuBar())
	{
		//Append menu
		wxMenu *menu = NULL;
		GetMenuBar()->FindItem(XRCID("ID_MENU_LAYOUT_DELETE"), &menu);
		
		if(menu)
		{
			int id = menu->FindItem(name);
			if(id != wxNOT_FOUND)
			{
				menu->Remove(id);
				m_layouts.erase(id);
			}		
		}
	}
}

void MainFrame::AddLayout(wxString name)
{
	AppendLayoutToMenu(name);
	layoutControl->AddLayout(name);
}

void MainFrame::RemoveLayout(wxString name)
{	
	if(layoutControl->RemoveLayout(name))
	{
		RemoveLayoutFromMenu(name);
	}
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENU_TITLE_BAR
 */

void MainFrame::OnMenuTitleBarClick( wxCommandEvent& event )
{
	long style = GetWindowStyle();

	if(event.IsChecked())
	{		
		style |= wxCAPTION | wxSYSTEM_MENU | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX;
		SetWindowStyle(style);


		//Without this, need go to other window and select this again to show the title bar
		Show(false);
		Show(true);

	}
	else
	{			
		Maximize(true);

		style &= ~(wxCAPTION | wxSYSTEM_MENU | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);
		SetWindowStyle(style);		
	}
}


/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENUITEM
 */

void MainFrame::OnMenuExitClick( wxCommandEvent& event )
{
	Close();	
}

void MainFrame::OnMenuNewClick( wxCommandEvent& event )
{
	/***** oryx
	bool bNewOk = false;

	if (GameControl::Get()->Modified())
	{
		int answer = wxMessageBox(wxT("This will discard the current game.\nProceed anyway?"), wxT("Confirm"), wxYES_NO | wxCENTRE);

		if(answer == wxYES)
		{			
			bNewOk = true;
		}
	}
	else
	{
		bNewOk = true;
	}
	
	if(bNewOk)
	{
		GameControl::Get()->NewGame();
		UndoControl::Get()->Clear();
		
		ActorProperty::Destroy();
	}
	oryx********/
}

void MainFrame::SetupMRU()
{
	wxMenu *menu = NULL;
	wxMenuItem *menuItem = GetMenuBar()->FindItem(XRCID("ID_MENU_EXIT"), &menu);

	if(menuItem && menu)
	{		
		wxConfig config("Oryx");
		mru.UseMenu(menu);
		mru.Load(config);		
	}

}


void MainFrame::OnMRUFile(wxCommandEvent& event)
{
    wxString file(mru.GetHistoryFile(event.GetId() - wxID_FILE1));
    if (!file.empty())
	{
		/*** oryx
		LoadSaveGame::Load(file.mbc_str(), true);
		***/
	}
}

void MainFrame::OnMenuOpenClick( wxCommandEvent& event )
{
	wxFileDialog* OpenDialog = new wxFileDialog(
		this, _("Load Game"), wxEmptyString, wxEmptyString, 
		_("Ged files (*.ged)|*.ged"), wxFD_OPEN, wxDefaultPosition);

	if (OpenDialog->ShowModal() == wxID_OK)
	{
		wxConfig config("Oryx");
		mru.AddFileToHistory(OpenDialog->GetPath());
		mru.Save(config);

		/***** oryx
		if(LoadSaveGame::Load(OpenDialog->GetPath().mbc_str(), true))
		{			
			wxConfig config("Oryx");
			mru.AddFileToHistory(OpenDialog->GetPath());
			mru.Save(config);
		}
		else
		{
			//mru.Remove(file);
					

			wxMessageBox(wxT("Can't load this project"), wxT("Error"), wxOK | wxCENTRE);
			GameControl::Get()->NewGame();
			UndoControl::Get()->Clear();
		}

		
		//SetTitle(wxString("Edit - ") << OpenDialog->GetFilename()); // Set the Title to reflect the file open
		*********/
	}
}

/******** oryx
void MainFrame::OnMenuLayoutSaveAsClick( wxCommandEvent& event )
{
	DlgSaveLayout dialog(true);
	dialog.ShowModal();
}


void MainFrame::OnMenuLayoutRestoreClick( wxCommandEvent& event )
{
	layoutControl->LoadCurrent();	 
}




void MainFrame::OnMenuLayoutSaveClick( wxCommandEvent& event )
{
	layoutControl->SaveCurrent();
}



void MainFrame::OnMenuLayoutDeleteClick( wxCommandEvent& event )
{
	DlgSaveLayout dialog(false);
	dialog.ShowModal(); 
}
*************/

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENU_LAYOUT_RESET
 */

void MainFrame::OnMenuLayoutResetClick( wxCommandEvent& event )
{
	int answer = wxMessageBox(wxT("Do you want load the original layout configuration?"), wxT("Confirm"), wxYES_NO | wxCENTRE);

	if(answer == wxYES)
	{
		layoutControl->LoadDefault();
		/***** oryx
		panelProperty->ResetState();
		******/
		//pBehavior->ResetState();
	}
}

void MainFrame::OnMove(wxMoveEvent & event)
{
	/******* oryx
	//Need to refresh DirectX window
	if(sdlPanel && sdlPanel->IsShown()) 
	{
		sdlPanel->Show(false);
		sdlPanel->Show(true);

		if(GameControl::Get() && GameControl::Get()->getGameMode() && !GameControl::Get()->getFullScreen())
		{
			sdlPanel->SetFocus();
		}
	}
	***********/
	
	if(!IsMaximized())
	{
		wxRect m_NonMaximizedRect(wxIFMLayoutControl::getNonMaximizedFrameRect());
		m_NonMaximizedRect.SetPosition(GetRect().GetPosition());
		wxIFMLayoutControl::setNonMaximizedFrameRect(m_NonMaximizedRect);
	}

	event.Skip();
}

void MainFrame::OnSize(wxSizeEvent & event)
{
	//Need to refresh DirectX window
	/*if(sdlPanel && sdlPanel->IsShown()) 
	{
		//sdlPanel->Show(false);
		//sdlPanel->Show(true);

		//if(m_ifm) m_ifm->UpdateConfiguration();

		EngineTick();
	}*/

	bool bMax = IsMaximized();

	if(!bMaximized && !bMax)
	{
		wxIFMLayoutControl::setNonMaximizedFrameRect(GetRect());
	}

	if(bMaximized && !bMax)
	{
		//Window restored
		mainFrame->SetSize(wxIFMLayoutControl::getNonMaximizedFrameRect());
	}

	bMaximized = bMax;

	event.Skip();
}

void MainFrame::OnIconize(wxIconizeEvent & event)
{
	event.Skip();
}

void MainFrame::OnMaximize(wxMaximizeEvent & event)
{
	bMaximized = true;
	event.Skip();
}

void MainFrame::OnDropFiles(wxDropFilesEvent & event)
{
	if(event.GetNumberOfFiles() > 0 && event.GetFiles())
	{
		/******** oryx
		//File dropped, send a SDL event
		static char fileName[256];
		SDL_Event sdlEvent;
		
		memset(&sdlEvent, 0, sizeof(SDL_Event));
		memcpy(fileName, event.GetFiles()[0].GetData(), event.GetFiles()[0].Length());
		
		sdlEvent.type = SDL_DROPFILES;
		sdlEvent.user.data1 = fileName;
		SDL_PushEvent(&sdlEvent);
		**********/
	}
}



/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for ID_GAME_MODE
 */

void MainFrame::OnGameModeClick( wxCommandEvent& event )
{
	/********* oryx
	if(!GameControl::Get()->getGameMode())
	{
		MainPanel::Get()->OnButton(NULL, BT_GAME_MODE);
		while(EngineTick() && GameControl::Get()->getGameMode());
	}
	********/
}

void MainFrame::OnGameObjectClick( wxCommandEvent& event )
{
	CCLayer *layer = HelloWorld::get();
	layer->setPosition(ccp(200, 200));

	CCSprite* pSprite = CCSprite::create("Cocos2d-X.png");
	pSprite->setPosition(ccp(480, 320));
	layer->addChild(pSprite, 0);

	Hierarchy::get()->AppendItem(NULL, 480, 320);

	GLCanvas::get()->Refresh(false);
}

void MainFrame::OnLayoutState(wxLayoutStateEvent& event)
{
	/******* oryx
	if(panelProperty && pBehavior)
	{
		switch(event.GetType())
		{
		case LAYOUT_STATE_SAVE:
			panelProperty->SaveState(*event.GetOutputStream());
			//pBehavior->SaveState(*event.GetOutputStream());
			break;
			
		case LAYOUT_STATE_LOAD:
			panelProperty->LoadState(*event.GetInputStream());
			//pBehavior->LoadState(*event.GetInputStream());
			break;
		}
	}
	*********/
}

/***** oryx
void MainFrame::OnBehaviorBlockSelected( wxCommandEvent &event )
{
	//Forwad the event to the Property Panel
	panelProperty->ProcessEvent(event);   
}
***/